# -*- coding: UTF-8 -*- 

import sys
from twisted.internet.protocol import Factory 
from twisted.protocols.basic import LineReceiver
from twisted.protocols.basic import LineOnlyReceiver 
from twisted.internet import reactor 
from twisted.python import log
from twisted.python.logfile import DailyLogFile
from data_operation import DataOperation as op
import datetime
import logger as Logger


logger = Logger.init()

class DataReceiver(LineReceiver): 

    def __init__(self, devices):
        self.devices = devices
        self.device = None
        self.state = 0

    def lineReceived(self, data):
        logger.debug('line_receive ' + str(data))
        self.sendLine('test_reply_line')
        
    def dataReceived(self, data):

        data = list(data)

        dt = datetime.datetime.now()
        logger.debug(dt)

        logger.debug('source data:')
        logger.debug(data)

        result_gateway = self.operate_gateway(data)
        logger.debug('operate_gateway result: '+str(result_gateway))

        result_1, deviceinfo = self.operate_device(data)
        logger.debug('operate_device result: '+str(result_1))
        logger.debug('operate_device device_detail: '+str(deviceinfo))
        if result_1:
            if deviceinfo is None:
                logger.debug('write data')
                logger.debug(data[1:len(data)])
                self.transport.write(''.join(data[1:len(data)]))
            else:
                logger.debug('lol')
                logger.debug(list(deviceinfo))
                self.transport.write(deviceinfo)

        result_2 = self.operate_data(data)
        logger.debug('operate_data result: '+str(result_2))
        
    def getId(self): 
        return str(self.transport.getPeer()) 
        
    def connectionMade(self): 
        print "New User Login:", self.getId() 
        logger.debug('get client ' + str(self.transport.getPeer())) 
        logger.debug(self.transport.getPeer().host)
            
    def connectionLost(self, reason): 
        logger.debug('lost client ' + str(self.transport.getPeer()))
        logger.debug('reason ' + str(reason))

        if self.devices.has_key(self.device):
            del self.devices[self.device]

    def operate_device(self, data_device):

        if len(data_device) == 29:

            file_object = open('log/device_config.txt', 'a')
            file_object.write(str(datetime.datetime.now())+'---------\n'+str(data_device)+'\n------------------------------------------------------------------------------\n ')
            file_object.close()

            data_type = ord(data_device[0])
            tag = data_device[1]
            data_device = data_device[2:len(data_device)]

            if data_type != 5:
                logger.debug('data_type: '+str(data_type))
                return True, None

            deviceid = op.get_device(data_device,1)
            if deviceid is None:
                return True, None

            logger.debug(deviceid)

            deviceinfo = op.update_device(data_device, deviceid)

            file_object = open('log/device_config.txt', 'a')
            file_object.write(str(datetime.datetime.now())+'---------\n'+str(list(deviceinfo))+'\n------------------------------------------------------------------------------\n ')
            file_object.close()

            return True, tag+deviceinfo
        else:
            return False, None

    def operate_data(self, data):

        if len(data) == 897:

            data_type = ord(data[0])
            if data_type != 6:
                logger.debug(str(data_type))
                return False

            data = data[1:len(data)]

            deviceid = op.get_device(data,2)
            if deviceid is None:
               return False, None

            logger.debug(deviceid)

            file_object = open('log/device_temp_data.txt', 'a')#open('log/device_'+str(deviceid)+'_data.txt', 'a')
            file_object.write(str(datetime.datetime.now())+'---------\n'+str(data)+'\n------------------------------------------------------------------------------\n ')
            file_object.close()

            result = op.operate_daily_data(deviceid, data)
            return True

        else:

            return False

    def operate_gateway(self, data):

        if len(data) == 10:

            data_type = ord(data[0])
            if data_type != 7:
                logger.debug(str(data_type))
                return False

            ip = self.transport.getPeer().host

            logger.debug('gateway :'+ip)
            return op.get_gateway(ip)

        else:
            return False

                           
class DataFactory(Factory): 
    def __init__(self):
        self.devices = {}

    def buildProtocol(self, addr):
        return DataReceiver(self.devices)
        
                        
reactor.listenTCP(12345, DataFactory())
reactor.run()